package com.litchi.fragment;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.listener.FindCallback;
import cn.bmob.v3.listener.FindListener;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnPullEventListener;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshBase.State;
import com.handmark.pulltorefresh.library.PullToRefreshScrollView;
import com.lib.uil.ToastUtils;
import com.litchi.R;
import com.litchi.activity.DetailActivity;
import com.litchi.activity.FavorActivity;
import com.litchi.activity.MainActivity;
import com.litchi.activity.OrdersActivity;
import com.litchi.activity.SearchActivity;
import com.litchi.adapter.GoodsHomeGridAdapter;
import com.litchi.adapter.MyPagerAdapter;
import com.litchi.app.MyApplication;
import com.litchi.bean.Goods;
import com.litchi.bean.GoodsHistory;
import com.litchi.bean.HomeGoods;
import com.litchi.utils.Constants;

/**
 *
 * 
 */
public class HomeFragment extends Fragment implements OnClickListener {

	private Context mContext;
	private PullToRefreshScrollView mPtrScrollView;
	private LinearLayout mLinearLayout1;
	private ViewPager mPager;
	private ImageView desImg1, desImg2, desImg3;
	private ImageView disCoountImg1, disCoountImg2, disCoountImg3, disCoountImg4, disCoountImg5;
	private ImageView mRecomImg1, mRecomImg2, mRecomImg3, mRecomImg4;
	private ImageView mSpecialImg1, mSpecialImg2, mSpecialImg3, mSpecialImg4;
	private GoodsHistory[] mInfos;
	private View layout;
	private com.litchi.utils.MyGridView mGridView;
	private HorizontalScrollView mScrollView, mScrollView2;
	private View errorView;// 错误时显示view
	private TextView reloadText;
	private List<HomeGoods> mList;
	private List<HomeGoods> mTopBannerList = new ArrayList<HomeGoods>();
	private List<HomeGoods> mDesImgList = new ArrayList<HomeGoods>();
	private List<HomeGoods> mDiscountImgList = new ArrayList<HomeGoods>();
	private List<HomeGoods> mRecomImgList = new ArrayList<HomeGoods>();
	private List<HomeGoods> mSpecialImgList = new ArrayList<HomeGoods>();

	private MyApplication mApplication;

	private int page = 0;
	public static int GRID_ITEM_NUM = 8;
	private GoodsHomeGridAdapter mGoodsHomeGridAdapter;
	List<Goods> mGridGoodsList = new ArrayList<Goods>();

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

		if (layout != null) {
			// 防止多次new出片段对象，造成图片错乱问题
			return layout;
		}
		mContext = getActivity();
		layout = inflater.inflate(R.layout.fragment_home, container, false);
		errorView = (View) layout.findViewById(R.id.error);
		reloadText = (TextView) layout.findViewById(R.id.reload);
		reloadText.setOnClickListener(this);
		initView();

		return layout;
	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		initData();
	}

	@SuppressLint("NewApi")
	@SuppressWarnings({ "unchecked", "rawtypes" })
	private void initView() {
		mApplication = (MyApplication) mContext.getApplicationContext();

		// part of title
		layout.findViewById(R.id.img_home_category).setOnClickListener(this);// logo监听
		layout.findViewById(R.id.img_home_search_code).setOnClickListener(this);// 搜索框监听
		layout.findViewById(R.id.layout_home_search).setOnClickListener(this);
		// part of banner
		mPager = (ViewPager) layout.findViewById(R.id.banner_pager);
		// part of menu
		layout.findViewById(R.id.menu_my_focus).setOnClickListener(this);
		layout.findViewById(R.id.menu_order_search).setOnClickListener(this);
		layout.findViewById(R.id.menu_my_brand).setOnClickListener(this);
		layout.findViewById(R.id.menu_mine).setOnClickListener(this);
		// part of bargain
		layout.findViewById(R.id.layout_discount);
		disCoountImg1 = (ImageView) layout.findViewById(R.id.img_discount_1);
		disCoountImg2 = (ImageView) layout.findViewById(R.id.img_discount_2);
		disCoountImg3 = (ImageView) layout.findViewById(R.id.img_discount_3);
		disCoountImg4 = (ImageView) layout.findViewById(R.id.img_discount_4);
		disCoountImg5 = (ImageView) layout.findViewById(R.id.img_discount_5);
		disCoountImg1.setOnClickListener(this);
		disCoountImg2.setOnClickListener(this);
		disCoountImg3.setOnClickListener(this);
		disCoountImg4.setOnClickListener(this);
		disCoountImg5.setOnClickListener(this);

		desImg1 = (ImageView) layout.findViewById(R.id.img_discount_banner);

		// part of recom
		mRecomImg1 = (ImageView) layout.findViewById(R.id.img_recom_1);
		mRecomImg1.setOnClickListener(this);
		mRecomImg2 = (ImageView) layout.findViewById(R.id.img_recom_2);
		mRecomImg2.setOnClickListener(this);
		mRecomImg3 = (ImageView) layout.findViewById(R.id.img_recom_3);
		mRecomImg3.setOnClickListener(this);
		mRecomImg4 = (ImageView) layout.findViewById(R.id.img_recom_4);
		mRecomImg4.setOnClickListener(this);
		desImg2 = (ImageView) layout.findViewById(R.id.img_recomm_banner);

		// part of special
		mSpecialImg1 = (ImageView) layout.findViewById(R.id.img_special_1);
		mSpecialImg1.setOnClickListener(this);
		mSpecialImg2 = (ImageView) layout.findViewById(R.id.img_special_2);
		mSpecialImg2.setOnClickListener(this);
		mSpecialImg3 = (ImageView) layout.findViewById(R.id.img_special_3);
		mSpecialImg3.setOnClickListener(this);
		mSpecialImg4 = (ImageView) layout.findViewById(R.id.img_special_4);
		mSpecialImg4.setOnClickListener(this);
		desImg3 = (ImageView) layout.findViewById(R.id.img_special_banner);

		mLinearLayout1 = (LinearLayout) layout.findViewById(R.id.LinearLayout1);
		mPtrScrollView = (PullToRefreshScrollView) layout.findViewById(R.id.ptrScrollView_home);
		mPtrScrollView.setOnRefreshListener(new OnRefreshListener<ScrollView>() {
			public void onRefresh(PullToRefreshBase<ScrollView> refreshView) {
				initData();
			}
		});
		mPtrScrollView.setOnPullEventListener(new OnPullEventListener() {

			@SuppressWarnings("rawtypes")
			@Override
			public void onPullEvent(PullToRefreshBase refreshView, State state, Mode direction) {
				// TODO Auto-generated method stub

				BmobQuery<Goods> query = new BmobQuery<Goods>();
				query.setLimit(GRID_ITEM_NUM);
				query.setSkip(page * GRID_ITEM_NUM);
				query.findObjects(mContext, new FindListener<Goods>() {

					@Override
					public void onError(int arg0, String arg1) {
						// TODO Auto-generated method stub

					}

					@Override
					public void onSuccess(List<Goods> arg0) {
						// TODO Auto-generated method stub
						if (arg0.size() == 0) {
							layout.findViewById(R.id.grid_foot).setVisibility(View.VISIBLE);
							mPtrScrollView.setMode(Mode.PULL_FROM_START);

						} else {
							page++;
							mGridGoodsList.addAll(arg0);
							mGoodsHomeGridAdapter.notifyDataSetChanged();
							mGridView.notifyAll();
						}

					}
				});
			}

		});
		 
		
		
		mScrollView = (HorizontalScrollView) layout.findViewById(R.id.layout_recom_banner);
		mScrollView2 = (HorizontalScrollView) layout.findViewById(R.id.layout_special_banner);
		mGridView = (com.litchi.utils.MyGridView) layout.findViewById(R.id.home_gridView);
		mGoodsHomeGridAdapter = new GoodsHomeGridAdapter(mContext, mGridGoodsList);
		mGridView.setAdapter(mGoodsHomeGridAdapter);
		mGridView.setOnItemClickListener(new AdapterView.OnItemClickListener(){

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(mContext, DetailActivity.class);
				intent.putExtra(Constants.GOODS_KEY, mGridGoodsList.get(position));
				mContext.startActivity(intent);
			}
			
		});
		 
	}

	public void initData() {

		if (mList != null) {
			mList.clear();

		}

		BmobQuery<HomeGoods> query = new BmobQuery<HomeGoods>("HomeGoods");
		query.findObjects(mContext, new FindCallback() {

			@Override
			public void onFailure(int arg0, String arg1) {
				// TODO Auto-generated method stub
				Log.d(Constants.LOG, arg1.toString());
				mLinearLayout1.setVisibility(View.GONE);
				layout.findViewById(R.id.progressBar).setVisibility(View.GONE);
				errorView.setVisibility(View.VISIBLE);
				mPtrScrollView.onRefreshComplete();
			}

			@Override
			public void onSuccess(JSONArray arg0) {
				// TODO Auto-generated method stub
				errorView.setVisibility(View.GONE);
				layout.findViewById(R.id.progressBar).setVisibility(View.GONE);
				mLinearLayout1.setVisibility(View.VISIBLE);
				Log.d(Constants.LOG, arg0.toString());
				Type type = new TypeToken<List<HomeGoods>>() {
				}.getType();
				mList = new Gson().fromJson(arg0.toString(), type);

				Log.d(Constants.LOG, "" + mList.size());

				for (int i = 0; i < mList.size(); i++) {

					HomeGoods mHomeGoods = mList.get(i);
					if (mHomeGoods.getHomeType().equals("topbanner")) {

						mTopBannerList.add(mHomeGoods);

					} else if (mHomeGoods.getHomeType().equals("discount")) {
						mDiscountImgList.add(mHomeGoods);
					} else if (mHomeGoods.getHomeType().equals("recommend")) {
						mRecomImgList.add(mHomeGoods);
					} else if (mHomeGoods.getHomeType().equals("des")) {
						mDesImgList.add(mHomeGoods);
					} else if (mHomeGoods.getHomeType().equals("special")) {
						mSpecialImgList.add(mHomeGoods);
					}

				}
				initPager();
				initDesImg();
				initDiscountImg();
				initRecomImg();
				initSpecialImg();
				mPtrScrollView.onRefreshComplete();
			}

		});

	}

	private void activeBrand() {
		MainActivity activity = (MainActivity) getActivity();
		activity.activeBrand();
	}

	private void activeMine() {
		MainActivity activity = (MainActivity) getActivity();
		activity.activeMine();
	}

	@Override
	public void onDestroyView() {
		super.onDestroyView();
		// 将layout从父组件中移除
		ViewGroup parent = (ViewGroup) layout.getParent();
		parent.removeView(layout);
	}

	private void initPager() {

		if (mTopBannerList.size() >= 4) {

			List<ImageView> images = new ArrayList<>();

			ImageView image1 = new ImageView(mContext);
			ImageView image2 = new ImageView(mContext);
			ImageView image3 = new ImageView(mContext);
			ImageView image4 = new ImageView(mContext);

			image1.setOnClickListener(this);
			image2.setOnClickListener(this);
			image3.setOnClickListener(this);
			image4.setOnClickListener(this);

			image1.setTag(mTopBannerList.get(0).getGoodsId());
			image2.setTag(mTopBannerList.get(1).getGoodsId());
			image3.setTag(mTopBannerList.get(2).getGoodsId());
			image4.setTag(mTopBannerList.get(3).getGoodsId());

			mApplication.imgLoader.displayImage(Constants.HTTP_FILE + mTopBannerList.get(0).getShowImg().getUrl(),
					image1);
			mApplication.imgLoader.displayImage(Constants.HTTP_FILE + mTopBannerList.get(1).getShowImg().getUrl(),
					image2);
			mApplication.imgLoader.displayImage(Constants.HTTP_FILE + mTopBannerList.get(2).getShowImg().getUrl(),
					image3);
			mApplication.imgLoader.displayImage(Constants.HTTP_FILE + mTopBannerList.get(3).getShowImg().getUrl(),
					image4);
			images.add(image1);
			images.add(image2);
			images.add(image3);
			images.add(image4);
			MyPagerAdapter adapter = new MyPagerAdapter(images);
			mPager.setAdapter(adapter);

		}
	}

	public void initDesImg() {
		if (mDesImgList.size() >= 3) {

			desImg1.setTag(mDesImgList.get(0).getGoodsId());
			desImg2.setTag(mDesImgList.get(1).getGoodsId());
			desImg3.setTag(mDesImgList.get(2).getGoodsId());

			mApplication.imgLoader.displayImage(Constants.HTTP_FILE + mDesImgList.get(0).getShowImg().getUrl(),
					desImg1);
			mApplication.imgLoader.displayImage(Constants.HTTP_FILE + mDesImgList.get(1).getShowImg().getUrl(),
					desImg2);
			mApplication.imgLoader.displayImage(Constants.HTTP_FILE + mDesImgList.get(2).getShowImg().getUrl(),
					desImg3);
		}
	}

	public void initDiscountImg() {
		if (mDiscountImgList.size() >= 5) {

			disCoountImg1.setTag(mDiscountImgList.get(0).getGoodsId());
			disCoountImg2.setTag(mDiscountImgList.get(1).getGoodsId());
			disCoountImg3.setTag(mDiscountImgList.get(2).getGoodsId());
			disCoountImg4.setTag(mDiscountImgList.get(3).getGoodsId());
			disCoountImg5.setTag(mDiscountImgList.get(4).getGoodsId());

			mApplication.imgLoader.displayImage(Constants.HTTP_FILE + mDiscountImgList.get(0).getShowImg().getUrl(),
					disCoountImg1);
			mApplication.imgLoader.displayImage(Constants.HTTP_FILE + mDiscountImgList.get(1).getShowImg().getUrl(),
					disCoountImg2);
			mApplication.imgLoader.displayImage(Constants.HTTP_FILE + mDiscountImgList.get(2).getShowImg().getUrl(),
					disCoountImg3);
			mApplication.imgLoader.displayImage(Constants.HTTP_FILE + mDiscountImgList.get(3).getShowImg().getUrl(),
					disCoountImg4);
			mApplication.imgLoader.displayImage(Constants.HTTP_FILE + mDiscountImgList.get(4).getShowImg().getUrl(),
					disCoountImg5);

		}
	}

	public void initRecomImg() {
		if (mRecomImgList.size() > 0) {

			mRecomImg1.setTag(mRecomImgList.get(0).getGoodsId());
			mRecomImg2.setTag(mRecomImgList.get(1).getGoodsId());
			mRecomImg3.setTag(mRecomImgList.get(2).getGoodsId());
			mRecomImg4.setTag(mRecomImgList.get(3).getGoodsId());

			mApplication.imgLoader.displayImage(Constants.HTTP_FILE + mRecomImgList.get(0).getShowImg().getUrl(),
					mRecomImg1);
			mApplication.imgLoader.displayImage(Constants.HTTP_FILE + mRecomImgList.get(1).getShowImg().getUrl(),
					mRecomImg2);
			mApplication.imgLoader.displayImage(Constants.HTTP_FILE + mRecomImgList.get(2).getShowImg().getUrl(),
					mRecomImg3);
			mApplication.imgLoader.displayImage(Constants.HTTP_FILE + mRecomImgList.get(3).getShowImg().getUrl(),
					mRecomImg4);
		}
	}

	public void initSpecialImg() {
		if (mSpecialImgList.size() > 0) {

			mSpecialImg1.setTag(mSpecialImgList.get(0).getGoodsId());
			mSpecialImg2.setTag(mSpecialImgList.get(1).getGoodsId());
			mSpecialImg3.setTag(mSpecialImgList.get(2).getGoodsId());
			mSpecialImg4.setTag(mSpecialImgList.get(3).getGoodsId());

			mApplication.imgLoader.displayImage(Constants.HTTP_FILE + mSpecialImgList.get(0).getShowImg().getUrl(),
					mSpecialImg1);
			mApplication.imgLoader.displayImage(Constants.HTTP_FILE + mSpecialImgList.get(1).getShowImg().getUrl(),
					mSpecialImg2);
			mApplication.imgLoader.displayImage(Constants.HTTP_FILE + mSpecialImgList.get(2).getShowImg().getUrl(),
					mSpecialImg3);
			mApplication.imgLoader.displayImage(Constants.HTTP_FILE + mSpecialImgList.get(3).getShowImg().getUrl(),
					mSpecialImg4);
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.img_home_category: // 切换到分类
			activeBrand();
			break;
		case R.id.img_home_search_code: // 二维码扫描
			((MainActivity) getActivity()).scanQRCode();
			break;
		case R.id.layout_home_search:
			gotoSearch();
			break;
		case R.id.menu_my_focus: // 我的关注
			startActivity(new Intent(getActivity(), FavorActivity.class));
			break;
		case R.id.menu_order_search: // 订单
			if (((MainActivity) mContext).getLogined()) {
				startActivity(new Intent(getActivity(), OrdersActivity.class));
			} else {
				ToastUtils.showToast(mContext, "请先登录...");
			}
			break;

		case R.id.menu_my_brand: // 品牌
			activeBrand();
			break;
		case R.id.menu_mine: // 我的
			activeMine();
			break;
		case R.id.reload:
			initData();
			break;
		default:

			int goodsId = (int) v.getTag();
			BmobQuery<Goods> query = new BmobQuery<Goods>("Goods");
			query.addWhereEqualTo("goodsId", goodsId);
			query.setLimit(50);
			query.findObjects(mContext, new FindListener<Goods>() {

				@Override
				public void onError(int arg0, String arg1) {
					// TODO Auto-generated method stub
					ToastUtils.showToast(mContext, "发生未知错误");
				}

				@Override
				public void onSuccess(List<Goods> arg0) {
					// TODO Auto-generated method stub

					Intent intent = new Intent(mContext, DetailActivity.class);
					intent.putExtra(Constants.GOODS_KEY, arg0.get(0));
					startActivity(intent);
				}

			});
			break;
		}
	}

	/**
	 * 跳转到搜索框
	 * 
	 */
	private void gotoSearch() {
		Intent intent = new Intent(getActivity(), SearchActivity.class);
		startActivity(intent);
		// activity开启无动画
		getActivity().overridePendingTransition(0, 0);
	}

}
